package com.cy.store.service.impl;

import com.cy.store.entity._Address;
import com.cy.store.repository.AddressRepository;
import com.cy.store.service.IAddressService;
import com.cy.store.service.IDistrictService;
import com.cy.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AddressServiceImpl implements IAddressService {

    @Autowired
    private AddressRepository addressRepository;

    //区域类，优化新增输入
    @Autowired
    private IDistrictService districtService;

    @Value("${user.address.max-count}")
    private int maxCount;

    @Override
    public void addAddress(Integer uid, String username, _Address address) {
        Integer count = addressRepository.countByUid(uid);
        //判断地址存储是否达到上限,抛出AddressCountLimitException异常
        if( count >= maxCount) throw new AddressCountLimitException("用户地址存储超过上限");

        //补全数据：uid，isDefault默认地址，4项日志
        address.setUid(uid);
        Integer isDefault = count == 0 ? 1 : 0;
        address.setIsDefault(isDefault);
        address.setCreatedUser(username);
        address.setCreatedTime(new Date());
        address.setModifiedUser(username);
        address.setModifiedTime(new Date());
        //补全地址信息
        address.setProvinceName(districtService.getNameByCode(address.getProvinceCode()));
        address.setCityName(districtService.getNameByCode(address.getCityCode()));
        address.setAreaName(districtService.getNameByCode(address.getAreaCode()));

        //插入数据，并抛出异常InsertException
        if(addressRepository.save(address) == null) throw new InsertException("插入收获地址出现问题");
    }

    @Override
    public List<_Address> getByUid(Integer uid) {
        List<_Address> list = addressRepository.findAllByUidOrderByIsDefaultDescCreatedTimeDesc(uid);
        for(_Address address:list){
            address.setUid(null);
            address.setProvinceCode(null);
            address.setCityCode(null);
            address.setAreaCode(null);
            address.setCreatedUser(null);
            address.setCreatedTime(null);
            address.setModifiedUser(null);
            address.setModifiedTime(null);
        }
        return list;
    }

    @Override
    public void setDefault(Integer aid, Integer uid, String username) {
        //查询收货地址数据，抛出抛出AddressNotFoundException
        _Address address = addressRepository.findById(aid).orElseThrow(()->new AddressNotFoundException("查询不到信息"));

        //判断查询结构的uid与当前操作uid一致与否，抛出AccessDeniedException
        if(!address.getUid().equals(uid)) throw new AccessDeniedException("非法访问");

        //所有收货地址设成非默认，根据返回值抛出UpdateException
        if(addressRepository.updateNonDefaultByUid(uid)<1) throw new UpdateException("设置默认收货地址时出现未知错误[1]");

        //设置指定aid地址为默认，根据返回值抛出UpdateException
        if(addressRepository.updateDefaultByAid(aid, username, new Date())!=1) throw new UpdateException("设置默认收货地址时出现未知错误[2]");

    }

    @Override
    public void delete(Integer aid, Integer uid, String username) {
        //通过aid获取地址，然后抛出AddressNotFoundException
        _Address address = addressRepository.findById(aid).orElseThrow(()->new AddressCountLimitException("收获地址不存在"));

        //判断uid相同否，抛出AccessDeniedException
        if(!address.getUid().equals(uid)) throw new AccessDeniedException("非法访问");

        //删除地址
        addressRepository.deleteById(aid);

        //判断刚删除的地址是不是默认地址，不是则可以返回结束了。是的话要重新设置一个默认地址
        if(address.getIsDefault()==0) return;

        //重设默认地址
        //判断是否还有收货地址
        if(addressRepository.countByUid(uid)==0) return;
        //设置最近修改地址为默认地址
        Page<_Address> addressPage = addressRepository.findAllByUidOrderByModifiedTimeDesc(uid, PageRequest.of(0,1));
        _Address lastModifiedAddress = addressPage.getContent().get(0);
        Integer row = addressRepository.updateDefaultByAid(lastModifiedAddress.getAid(), username, new Date());
        if(row != 1) throw new UpdateException("修改默认地址时候出错");
    }

    @Override
    public _Address getByAid(Integer aid, Integer uid) {
        //查询信息，抛AddressNotFoundException异常
        _Address address = addressRepository.findById(aid).orElseThrow(()->new AddressNotFoundException("尝试访问的收货地址数据不存在"));

        //检查是否非法访问
        if(!address.getUid().equals(uid)) throw new AccessDeniedException("非法访问");

        //优化数据
        address.setProvinceCode(null);
        address.setCityCode(null);
        address.setAreaCode(null);
        address.setCreatedUser(null);
        address.setCreatedTime(null);
        address.setModifiedUser(null);
        address.setModifiedTime(null);

        return address;
    }
}
